package demos;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Test {
	private BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(4);
	
	public static void main(String[] args) throws InterruptedException {
		Test test = new Test();
		Thread putThread = new Thread() {
			@Override
			public void run() {
				int i = 0;
				while(true) {
					try {
						test.queue.put(i);
						i++;
						
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		Thread takeThread = new Thread() {
			@Override
			public void run() {
				int i = 0;
				while(true) {
					try {
						System.out.print(String.format("% 3d", test.queue.take()));
						if(++i % 10 == 0)
							System.out.println(" size: " + test.queue.size());
						TimeUnit.MILLISECONDS.sleep(400);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		Thread takeThread1 = new Thread() {
			@Override
			public void run() {
				int i = 0;
				while(true) {
					try {
						System.out.print(String.format("% 3d", test.queue.take()));
						if(++i % 10 == 0)
							System.out.println(" size: " + test.queue.size());
						TimeUnit.MILLISECONDS.sleep(400);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		takeThread.start();
		takeThread1.start();
		putThread.start();
		
		TimeUnit.SECONDS.sleep(30);
		System.exit(0);
	}
}
